package org.example.server.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.common.context.BaseContext;
import org.example.common.properties.JwtProperties;
import org.example.common.result.Result;
import org.example.common.utils.JwtUtil;
import org.example.dto.MobileDTO;
import org.example.dto.UserDTO;
import org.example.entity.OrgInfo;

import org.example.entity.User;
import org.example.server.service.OrgInfoService;
import org.example.server.service.UserService;
import org.example.vo.UserVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/auht/mobile")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private OrgInfoService orgInfoService;

    String Code;

    @PostMapping("/code")
    private Result<String> getCode(@RequestBody MobileDTO mobileDTO) {
        log.info("根据手机号获取验证码");
        String account1 = mobileDTO.getMobile();
        String code = userService.getCode(account1);

        Code = code;
        return Result.success(code);
    }


    @PostMapping("/login")
    private Result<UserVO> login(@RequestBody UserDTO userDTO) {

        log.info("用户登录");


        userService.login(userDTO.getMobile(), userDTO.getCode(), Code);

        OrgInfo orgInfo = orgInfoService.selectById(1);

       // String currentId = BaseContext.getCurrentId();
        User user = userService.selectByMobile(userDTO.getMobile(),orgInfo.getHospitalNo());


        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("用户id", user.getUserId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        UserVO userVO = UserVO.builder().
                nickName(user.getUserNick()).
                hospitalName(orgInfo.getHospitalName()).
                hospitalNo(orgInfo.getHospitalNo()).
                avatarImg("https://haowallpaper.com/link/common/file/getCroppingImg/15942630369381760").
                accessToken(token).
                build();


        return Result.success(userVO);

    }

}
